package com.itqf.listen;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/12/19
 * @Time: 上午9:05
 */
@Component
public class RabbitMessageListener {

    @Resource
    private RedisTemplate redisTemplate;

    public RabbitMessageListener(){
        System.out.println("---->构建了RabbitListener");
    }

    /**
     * 处理消息
     * Message 消息对象
     */
    @RabbitListener(queues = "queue")
    public  void  getMessage(Message message, Channel channel){

        //得到消息的id
        Object id = message.getMessageProperties().getMessageId();
        Object messageId = redisTemplate.opsForValue().get("messageId");
        System.out.println(id+"----"+messageId);
        if (id!=null){
            //查看redis中是否有该消息
            if (messageId!=null&&(id==messageId||id.equals(messageId))){
                System.out.println(id+"消息已经消费过");
                return;
            }

        }

        try {
            System.out.println("接到消息--->"+new String(message.getBody()));
            System.out.println("处理消息");

            System.out.println("处理完毕");
            //手动确认
            /**
             * getDeliveryTag()
             */
            redisTemplate.opsForValue().set("messageId",id);

            int i = 10/0;//模拟消费者网络不好  重新消费消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
